<script>
  import $ from '../dfish.js'
  import {
    h
  } from 'vue'
  import THead from './TableTHead.vue'
  import Scroll from './Scroll.vue'

  export default {
    name: 'w-tbody',
    mixins: [THead, Scroll],
    inject: ['table'],
    props: ['br'],
    provide() {
      return {
        thead: null,
        provideInBody: true,
      }
    },
    created() {
      this.$watch(() => this.table.x, (x) => {
        this.x.scrollX = x.scrollX
        this.x.scrollY = this.table.fixed ? true : x.scrollY
      }, {
        immediate: true
      })
    },
    methods: {
      onScroll(e) {
        let t = this.table
        let hd = t.slotHooks.thead
        if (hd) {
          hd.el.scrollLeft = e.target.scrollLeft
        }
        let st = (t.table || t).scrollTable
        if (t.fixed) {
          if (t.table != st) t.table.scrollTop(e.target.scrollTop)
        } else {
          if (t.leftTable) {
            if (t.leftTable != st) t.leftTable.scrollTop(e.target.scrollTop)
          }
          if (t.rightTable) {
            if (t.rightTable != st) t.rightTable.scrollTop(e.target.scrollTop)
          }
        }
      },
      onScrollbarMousedown(e) {
        this.setScrollTable()
      },
      onScrollPosition(v) {
        let t = this.table
        if (t.leftTable || t.rightTable) {
           let el = this.el()
          if (el && v == 'left' || v == 'center' || v == 'right') {
            el.setAttribute('w-scroll-x', v)
          }
        }
      },
      setScrollTable(a) {
        let t = this.table;
        (t.table || t).scrollTable = t
      },
      html_slots() {
        return this.html_scroll_slots(this.html_tbody())
      }
    },
    computed: {
      inBody() {
        return true
      },
      html_class() {
        return ['w-vertical f-flex-1 f-oh', this.html_scroll_class, {
          'z-br': this.x.br,
          'z-hv': !this.table.fixed && this.table.scrollHover
        }]
      },
      html_props() {
        let t = this.table
        if (t.leftTable || t.rightTable || t.fixed) {
          return $.br.mobile ? {
            ontouchstart: this.setScrollTable
          } : {
            onwheel: e => {
              this.setScrollTable()
              t.fixed && (t.table.scrollHover = true)
            },
            onmouseenter: t.fixed && (e => {
              t.table.scrollHover = true
            }),
            onmouseleave: t.fixed && (e => {
              t.table.scrollHover = false
            })
          }
        }
      }
    },
    mounted() {
      this.el().setAttribute('w-scroll-x', 'left')
    }
  }
</script>
